package ch.il07.converter.persistence.impl.mysql.pooling;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import ch.il07.converter.persistence.exceptions.PersistenceException;

/**
 * @author Reto Hablützel
 * @author ncaspar
 */
public final class DbPoolPairManager {

	private static DbPoolPairManager instance = null;

	private Map<String, DbConnectionPoolPair> pools = new HashMap<String, DbConnectionPoolPair>();

	private DbPoolPairManager() {
	}

	public Map<String, DbConnectionPoolPair> getPools() {
		return this.pools;
	}

	public static DbPoolPairManager getInstance() {
		if (instance == null) {
			instance = new DbPoolPairManager();
		}
		return instance;
	}

	public void removePool(String name) {
		if (pools.containsKey(name)) {
			pools.remove(name);
		}
	}

	/**
	 * Fügt einen Pool zum Manager hinzu.
	 * 
	 * @param name
	 * @param pool
	 */
	public void addPool(String name, DbConnectionPoolPair pool) {
		pools.put(name, pool);

	}

	/**
	 * Gibt eine freie Connection des Pools pool zurück.
	 * 
	 * @param pool
	 * @return Connection
	 * @throws PersistanceException
	 * 
	 */
	public Connection getConnection(String pool) throws PersistenceException {
		if (!pools.containsKey(pool)) {
			throw new PersistenceException("No such pool available");
		}
		return pools.get(pool).getConnection();

	}

	/**
	 * Gibt eine besetzte Verbindung wieder frei.
	 * 
	 * @param pool
	 * @param connection
	 */
	public void putConnection(String pool, Connection connection) {
		if (pools.containsKey(pool)) {
			try {
				pools.get(pool).putConnection(connection);
			} catch (SQLException ex) {
			}
		}
	}

	@Override
	public String toString() {
		StringBuffer result = new StringBuffer();
		result.append("DbConnectionManager\n=========================\n");
		Object[] values = pools.values().toArray();
		Object[] keys = pools.keySet().toArray();
		for (int i = 0; i < values.length; ++i) {
			result.append("\nPool ");
			result.append(keys[i]);
			result.append("\n");
			result.append(values[i].toString());
			result.append("\n");
		}
		return result.toString();
	}
}
